{layout name="layout" /}

<script src="/static/md/js/ace/ace.js"></script>
<script src="/static/md/js/marked.js"></script>
<link href="/static/md/css/markdown.css" rel="stylesheet" />
<script src="/static/md/js/showPanel.js"></script>
<link href="/static/admin/css/editor.css" rel="stylesheet" />
<script>
    $(function(){
        $('#dialog').hide();
    })
</script>
<div id='bar'>
    <div id="topbar">

    </div>
    <div id="czbar">
        <input type="hidden" id="id" name="id" value="{$data.id}">
        <input style="font-size: 26px;width: 80%;padding-left: 10px;border: 0px none #FFFFFF;padding-top: 5px;" type="text"
            id="title" value="{$data.title}" placeholder="文章标题" />
        <select id="category">
            {foreach $categories as $key=>$val}
            <option value="{$key}" {eq name="data.cid" value="$key"}selected{/eq}> {$val} </option>
            {/foreach}
        </select>
        <button  type="button"  id="commit"> 保存 </button>
        <input type="text" id="summary" name="summary" value="{$data.summary}" placeholder="摘要">
    </div>
    <div id="toolbar">
        <img src="/static/md/img/bold.png" id="bold" onclick="insertText('**这里填写要加粗的文字**')" />
        <img src="/static/md/img/italic.png" id="italic" onclick="insertText('_这里填写要斜体的文字_')" />
        <img src="/static/md/img/hyperlink.png" id="hyperlink" onclick="insertText('[这里写连接的描述](这里填写连接地址)')" />
        <img src="/static/md/img/code.png" id="code" onclick="insertText('```\n这里插入代码\n```')" />
        <img src="/static/md/img/image.png" id="image" onclick="showDialog()" />
    </div>
</div>
<div id='container'>
    <div id='editor-column' class='pull-left'>
        <div id='panel-editor' style="height: 100%;">
            <!--编辑区-->
            <div class="editor-content" id="mdeditor" style="height: 100%;">{$data.content_md}</div>
        </div>
    </div>
    <div id='preview-column' class='pull-right'>
        <div id='panel-preview'>
            <!--显示区-->
            <div id="preview" class="markdown-body"></div>

        </div>
    </div>

    <div id="dialog">
        <div style="position: absolute;height: 40px;width: 100%;background: #FFFFFF;border-bottom: 1px solid gray;">
            <span style="position: absolute;left: 10px;top: 10px;color: gray;">插入图片</span>
            <img src="/static/md/img/X.png" style="height: 25px;width: 25px;position: absolute;right: 10px;top: 10px;cursor: pointer;"
                onclick="f_cancel()" />
        </div>
        <div>
            <form enctype="multipart/form-data" id="uploadForm">
                <div id="filediv">
                    <span style="background: gray;color: #FFFFFF;padding: 6px 10px;">选择图片</span>
                    <input type="text" id="fileName" style="height: 25px;width: 70%;" />
                    <input type="file" id="file" name="image" onchange="setFile()" />
                </div>
                <button type="button" id="upload" onclick="uploadFile()">上传</button>
            </form>
        </div>
        <img id="showImg" />
        <div style="position: absolute;bottom: 1px;width: 100%;height: 40px;border-top: 1px solid gray;">
            <button id="cancel" onclick="f_cancel()">取消</button>
            <button id="insert" onclick="insert()">插入</button>
        </div>
    </div>
</div>
<script>
    var imgUrl = ''; //上传图片返回的url

    var acen_edit = ace.edit('mdeditor'); //左侧编辑框
    acen_edit.setTheme('ace/theme/chrome');
    acen_edit.getSession().setMode('ace/mode/markdown');
    acen_edit.renderer.setShowPrintMargin(false);

    $("#preview").html(marked(acen_edit.getValue()));

    $("#mdeditor").keyup(function () { //给左侧编辑框添加事件，，当键盘抬起时，右侧实时显示左侧的md内容
        $("#preview").html(marked(acen_edit.getValue()));
    });

    function f_commit() {
        console.log($('#group').val());
    }
    //DownPanel是我自己写的一个提示，当鼠标移到该dom上，回显示相关提示
    $('#bold').DownPanel({
        render: '<span style="color:#ffffff;">加粗</span>',
        background: '#000000',
        top: ($('#bold').offset().top + 40),
        left: ($('#bold').offset().left)
    });
    $('#code').DownPanel({
        render: '<span style="color:#ffffff;">插入代码</span>',
        background: '#000000',
        top: ($('#code').offset().top + 40),
        left: ($('#code').offset().left)
    });
    $('#hyperlink').DownPanel({
        render: '<span style="color:#ffffff;">插入超链接</span>',
        background: '#000000',
        top: ($('#hyperlink').offset().top + 40),
        left: ($('#hyperlink').offset().left)
    });
    $('#image').DownPanel({
        render: '<span style="color:#ffffff;">插入图片</span>',
        background: '#000000',
        top: ($('#image').offset().top + 40),
        left: ($('#image').offset().left)
    });
    $('#italic').DownPanel({
        render: '<span style="color:#ffffff;">斜体</span>',
        background: '#000000',
        top: ($('#italic').offset().top + 40),
        left: ($('#italic').offset().left)
    });

    //左侧插入，用户插入一些特定方法
    function insertText(val) {
        acen_edit.insert(val); //光标位置插入
    }

    //选择图片后，用于显示图片路径
    function setFile() {
        $('#fileName').val($('#file').val());
    }

    //上传图片到服务器，返回图片地址
    function uploadFile() {
        if ($("#file").val() == '') {
            layer.msg("请选择要上传的文件", {
                icon: 6,
                time: 1000
            });
            return false;
        } else {
            var formData = new FormData($("#uploadForm")[0]);
            // console.log(formData);
            //ajax上传
            $.ajax({
                url: '{:url("/file_manager/upload")}',
                type: 'POST',
                async: true,
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (data) {
                    if (data.code == 2) {
                        // console.log(data.filename);
                        imgUrl = '/uploads/' + data.filename;
                        $('#showImg').attr('src', imgUrl);
                    } else {
                        layer.msg(data.msg, {
                            icon: 5,
                            time: 1000
                        });
                        return false;
                    }
                }
            })
        }
    }

    //插入图片弹窗取消
    function f_cancel() {
        $('#dialog').hide();
    }

    //插入图片
    function insert() {
        $('#dialog').hide();
        insertText('![这里写图片描述](' + imgUrl + ')')
    }

    //显示弹窗
    function showDialog() {
        $('#dialog').show();
    }

    // 检查titles是否重复
    $("#title").change(function(){
        $("#title").css('border', '0px none #FFFFFF');
        var title = $("#title").val();
        var id = $("#id").val();
        if (title) {
            $.post('/blog_article/title', {'title':title, 'id':id}, function(data){
                // console.log(data);
                if (data.code!=1) {
                    $("#title").css('border', 'solid 1px #f00');
                    layer.msg('标题已存在, 请更换标题!', {
                        icon: 5,
                        time: 1000
                    });
                    return false;
                }
            },'json');
        } else {
            $("#title").css('border', 'solid 1px #f00');
            layer.msg('标题不可为空!', {
                icon: 5,
                time: 1000
            });
            return false;
        }
    });

    function getFormData() {
        var title = $('#title').val();
        var cid = $('#category').val();
        var summary = $('#summary').val();
        var content_md = acen_edit.getValue();
        var content = marked(acen_edit.getValue());

        return {
            'title': title,
            'cid': cid,
            'summary': summary,
            'content_md': content_md,
            'content': content,
        };
    }

     // 提交文章
     $("#commit").click(function() {
        var data = getFormData();
        // console.log(data);
        // return 0;
        $.ajax({
            type: "post",
            url: '/blog_article/edit/{$data.id}',
            data:data,
            success: function(data){
                console.log(data.msg);
                if (data.code == 1) {
                    layer.msg(data.msg, {
                        icon: 6,
                        time: 2000
                    });
                    window.location.href=data.url;
                } else {
                    layer.msg(data.msg, {
                        icon: 5,
                        time: 2000
                    });
                    return false;
                }
            },
        })
    });
</script>